package com.tjvib.util.retrofit;

import static com.tjvib.Constants.TOKEN_NAME;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;

import com.tjvib.TJVIBAPP;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.SharedPreferencesUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 拦截器，配置统一的请求参数/header等
 */
public class BaseInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {//用于添加的请求头
        String token = UserManager.getInstance().getToken();
        LogUtil.d("UserManager token：" + token);

        Request original = chain.request();
        Request request;
        if (token == null || token.equals("")) {
            token = SharedPreferencesUtil.getToken(TJVIBAPP.getContext());
            UserManager.getInstance().setToken(token);
            LogUtil.d("SharedPreferencesUtil token：" + token);
        }

        request = original.newBuilder()
                .header("token", token)
                .method(original.method(), original.body())
                .build();
        Response response = chain.proceed(request);
        if (response.code() == 401) {
            token = SharedPreferencesUtil.getToken(TJVIBAPP.getContext());
            Request newRequest = original.newBuilder()
                    .header("token", token)
                    .method(original.method(), original.body())
                    .build();
            return chain.proceed(newRequest);
        }

        return response;
    }
}
